﻿using MediatR;
using RedDragon.Common.Domain.Supplier;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Supplieries
{
    /// <summary>
    /// 显示所有国家
    /// </summary>
    public class SearchCountryHandler : IRequestHandler<SearchCountryCommand, Result>
    {
        /// <summary>
        /// 所有国家仓储
        /// </summary>
        private readonly IBaseRepository<Countrys> _countryRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchCountryHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="countryRepository"></param>
        /// <param name="logger"></param>
        public SearchCountryHandler(IBaseRepository<Countrys> countryRepository,
                                    ILogger<SearchCountryHandler> logger)
        {
            _countryRepository = countryRepository;
            _logger = logger;
        }

        /// <summary>
        /// 显示所有国家
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(SearchCountryCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                //查询所有国家
                var query = await (await _countryRepository.GetAll()).ToListAsync();
                //判断是否有国家
                if (query.Count > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = query;
                    result.Msg = "获取所有国家成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "获取所有国家异常" + ex.Message;
                _logger.LogError("获取所有国家异常" + ex.Message);
            }
            return result;
        }
    }
}
